import { platformApi } from '../../api';
import type { PageResponse } from '../../api';
import type { PlatformRole } from '../../../types/platform';

// 平台角色查询参数
interface PlatformRoleQueryParams {
  page?: number;
  size?: number;
  current?: number;
  search?: string;
  code?: string;
  name?: string;
  status?: number;
  isBuiltin?: boolean;
}

/**
 * 通用API响应处理工具
 * 响应拦截器已经返回了实际数据，不需要再取.data
 */
const handleApiResponse = <T>(response: any): T => {
  return response as T;
};

/**
 * 平台权限管理相关API服务
 */
export const platformPermissionApiService = {
  /**
   * 分页查询角色及其菜单权限
   */
  getRolesWithMenusPage: async (params?: PlatformRoleQueryParams): Promise<PageResponse<PlatformRole & { menuCodes?: string[] }>> => {
    try {
      const query = {
        current: params?.page || params?.current || 1,
        size: params?.size || 10,
        code: params?.search || params?.code,
        name: params?.search || params?.name,
        status: params?.status,
        isBuiltin: params?.isBuiltin,
        ...params
      };
      
      const response = await platformApi.post('/api/v3/platform/permissions/roles/page', query);
      return handleApiResponse(response);
    } catch (error) {
      console.error('分页查询角色权限失败:', error);
      throw error;
    }
  },

  /**
   * 获取所有平台菜单
   */
  getAllMenus: async (): Promise<any[]> => {
    try {
      const response = await platformApi.get('/api/v3/platform/menus/all');
      return handleApiResponse(response);
    } catch (error) {
      console.error('获取菜单数据失败:', error);
      throw error;
    }
  },

  /**
   * 根据角色编码获取菜单编码列表
   */
  getRoleMenuCodes: async (roleCode: string): Promise<string[]> => {
    try {
      const response = await platformApi.get(`/api/v3/platform/permissions/role/${roleCode}/menu-codes`);
      return handleApiResponse(response);
    } catch (error) {
      console.error('获取角色菜单失败:', error);
      throw error;
    }
  },

  /**
   * 为角色分配菜单权限
   */
  assignMenusToRole: async (roleCode: string, menuCodes: string[]): Promise<void> => {
    try {
      await platformApi.post(`/api/v3/platform/permissions/role/${roleCode}/assign-menus`, menuCodes);
    } catch (error) {
      console.error('分配菜单权限失败:', error);
      throw error;
    }
  },

  /**
   * 检查权限
   */
  checkPermission: async (permission: string): Promise<boolean> => {
    try {
      const response = await platformApi.get('/api/v3/platform/auth/check-permission', {
        params: { permission },
      }) as any;
      return response;
    } catch (error) {
      throw error;
    }
  },

  /**
   * 检查菜单权限
   */
  checkMenuPermission: async (menuCode: string): Promise<boolean> => {
    try {
      const response = await platformApi.get('/api/v3/platform/auth/check-menu', {
        params: { menuCode },
      }) as any;
      return response;
    } catch (error) {
      throw error;
    }
  },
};

export { platformPermissionApiService as platformPermissionApi };
export default platformPermissionApiService;